package com.demo.bookstore.servlet;

import com.demo.bookstore.bean.User;
import com.demo.bookstore.service.UserService;
import com.demo.bookstore.service.impl.UserServiceImpl;
import com.demo.bookstore.vo.SysResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.beanutils.BeanUtils;
import org.thymeleaf.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Optional;

/**
 * @author ddone
 * @date 2024/3/13-20:17
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {
    private final UserService userService = new UserServiceImpl();
    private final ObjectMapper MAPPER = new ObjectMapper();

    public void toLogin(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        this.processTemplate("user/login", req, resp);
    }

    public void toRegist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        this.processTemplate("user/regist", req, resp);
    }


    public void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        User user = new User();
        user.setUsername(req.getParameter("username"));
        user.setPwd(req.getParameter("password"));
        User findUser = userService.findUserByUp(user);
        if (findUser != null) {
            // 登录成功 将用户信息保存到session中
            req.getSession().setAttribute("book_user", findUser);
            resp.sendRedirect(req.getContextPath() + "/index.html");
        } else {
            // 转发到登录页面, 并提示用户名或密码错误
            req.setAttribute("msg", "用户名或密码错误");
            // 直接用模板了 user页面下的login页面
            this.processTemplate("user/login", req, resp);
        }
    }

    public void regist(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = new User();
        try {
            BeanUtils.populate(user, req.getParameterMap());
        } catch (Exception e) {
            e.printStackTrace();
        }
        int rows = userService.insertUser(user);
        if (rows > 0) {
            resp.sendRedirect(req.getContextPath() + "/user?method=toLogin");
        } else {
            this.processTemplate("user/regist", req, resp);
        }
    }

    /**
     * 登出服务
     *
     * @param req
     * @param resp
     */
    public void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        // 1. 删除session信息
        req.getSession().removeAttribute("book_user");
        req.getSession().removeAttribute("cart");
        // 2. 重定向到系统首页
        resp.sendRedirect(req.getContextPath() + "/index.html");
    }


    public void checkUserName(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String username = req.getParameter("username");
        boolean isExist = userService.checkUserName(username);
        if(isExist){
            resp.getWriter().write(MAPPER.writeValueAsString(SysResult.fail(isExist)));
        }else {
            resp.getWriter().write(MAPPER.writeValueAsString(SysResult.success(isExist)));
        }

    }

    public void checkAuthCode(HttpServletRequest req,HttpServletResponse resp) throws IOException {
        String code = req.getParameter("code");
        String realCode = Optional.ofNullable(req.getSession().getAttribute("KAPTCHA_SESSION_KEY"))
                .map(Object::toString)
                .orElse("111112");

        SysResult sysResult = StringUtils.equalsIgnoreCase(code, realCode) ? SysResult.success("") : SysResult.fail("");
        resp.getWriter().write(MAPPER.writeValueAsString(sysResult));
    }
}
